<?php
namespace Home\Controller;

use Common\Model\GoodsAttrModel;
use Common\Model\CategoryModel;
use Common\Model\TypeAttrModel;
use Common\Model\GoodsModel;

use Think\Controller;

/**
 * 列表页管理控制器
 * Class IndexController
 * @package Home\Controller
 */
class ListController extends Controller
{
	//首页
	public function index ()
	{
		$headConf = [
				'js'=>['list'],
				'css'=>['index'],
				'title'=>'上一天堂'
		];
		$this->assign('headConf',$headConf);
		$cid = I('get.cid',0,'intval');
		//1.面包屑导航
		$fatherData = $this->getFather((new CategoryModel())->select(),$cid);
//		p($fatherData);
		//array_reverse 数组翻转
		$fatherData =array_reverse($fatherData);
		$this->assign('fatherData',$fatherData);
		//递归找子集
		$cids = $this->getSon((new CategoryModel())->select(),$cid);

		$cids[] = $cid;

		//在商品表中获取这些分类数据
		$gids = (new GoodsModel())->where("cid in (".implode(',',$cids).")")->getField('gid',true);
//		p($gids);
		//判断如果当前分类下面有商品
		if($gids)
		{
			$res = (new GoodsAttrModel())->alias('ga')
					->join("sh_type_attr ta on ga.aid=ta.aid")
					->where("ga.gid in (".implode(',',$gids).")")
					->group('gtvalue')->select();
//			p($res);
			//重组数组，将taid一样的放在一个组
			$temp = [];
			foreach($res as $k=>$v)
			{
				$temp[$v['aid']][] = $v;
			}
			$finalTemp = [];
			foreach($temp as $k=>$v)
			{
				$finalTemp[] = [
						'name'=>(new TypeAttrModel())->where("aid=$k")->getField("aname"),
						'value'=>$v,
				];
			}
			$this->assign('finalTemp',$finalTemp);
//			p($finalTemp);
			//筛选处理
			$param = isset($_GET['param']) ? explode('_',$_GET['param']) : array_fill(0,count($finalTemp),0);
			//p($param);
			$this->assign('param',$param);
			foreach($param as $k=>$v)
			{
				if($v)
				{//$v  gtid
					//根据gtid找到对应的gtvalue
					$gtvalue = (new GoodsAttrModel())->where("gtid=$v")->getField('gtvalue');
					//在根据gtvalue找到对应的商品id
					$fiterGids[] = (new GoodsAttrModel())->where("gtvalue='{$gtvalue}'")->getField('gid',true);
				}
			}
			//p($fiterGids);
			if($fiterGids)//如果存在筛选过后的gids
			{
				$finalGids = $fiterGids[0];

				foreach($fiterGids as $k=>$v)
				{
					//求完交集之后，要冲改变$finalGids
					$finalGids = array_intersect($finalGids,$v);
				}
				//最后再跟$gids求交集,$fiterGids在商品属性表中全部商品中查找的，
				//结果中有些不在我当前分类下面的
				$finalGids = array_intersect($fiterGids,$gids);
			}else{
				$finalGids = $gids;
			}
		}else{
			//说明该分类下面没有商品
			$finalGids = [];
		}

		$goodsData =(new CategoryModel())->alias('ca')
					->join("sh_goods g on ca.cid = g.cid")
					->find();
		//p($goodsData);
		$this->assign('goodsData',$goodsData);

		$this->display();
	}
	//找父级
	public function getFather($data,$cid){
		static  $temp =[];
		foreach($data as $k=>$v){
			if($v['cid']==$cid){
				$temp[] =$v;
				$this->getFather($data,$v['pid']);
			}
		}
		return $temp;
	}
	//找子集
	public function getSon($data,$cid)
	{
		static $temp = [];
		foreach($data as $k=>$v)
		{
			if($v['pid']==$cid)
			{
				$temp[] = $v['cid'];
				$this->getSon($data,$v['cid']);
			}
		}
		return $temp;
	}


}